package com.csusm.geoscience.tutor;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class Service {

	public String getLinks() {
		String result = null;
		InputStream is = null;
		StringBuilder sb=null;
		String retVal = null;
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	      //http post
		      try{
		           HttpClient httpclient = new DefaultHttpClient();
		           HttpPost httppost = new HttpPost("http://ouyangdev.cs.csusm.edu/databaseAccess.php");
		           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		           HttpResponse response = httpclient.execute(httppost);
		           HttpEntity entity = response.getEntity();
		           is = entity.getContent();
		           }catch(Exception e){
		               Log.e("log_tag", "Error in http connection"+e.toString());
		          }
		      //convert response to string
		      try{
		            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		            sb = new StringBuilder();
		            sb.append(reader.readLine() + "\n");
		
		            String line="0";
		            while ((line = reader.readLine()) != null) {
		                sb.append(line + "\n");
		            }
		            is.close();
		            result=sb.toString();
		      }catch(Exception e){
		            Log.e("log_tag", "Error converting result "+e.toString());
		      }
		      //paring data
		      
		      String[] rowsTemp;
		      /* delimiter */
		      String rdelimiter = ":::;::";
		      String cdelimiter = ":::::";
		      /* given string will be split by the argument delimiter provided. */
		      rowsTemp = result.split(rdelimiter);
		      /* print substrings */
		      for(int i =0; i < rowsTemp.length ; i++){
		        System.out.println(rowsTemp[i]);
		        
					String[] tempcolumn;
					String temprow = rowsTemp[i]; 
					tempcolumn = temprow.split(cdelimiter);
					for (int j = 0; j < tempcolumn.length; j++) {
						System.out.println("column "+ j+" ::::"+tempcolumn[j]);
						if(j==2  && tempcolumn[j]!=null)
							retVal = tempcolumn[2];
					}	       
					
		      }
		      return retVal;
	}
}
